/**
 * Copyright (c) 2024-2025 National Fundamental Software of China Co., Ltd.
 *
 * You should have find a copy of NFSChina License. If not, please contact us
 * by email <os_support@nfschina>
 *
**/

/*
    SPDX-FileCopyrightText: 2018 Roman Gilg <subdiff@gmail.com>
    SPDX-FileCopyrightText: 2018 Furkan Tokac <furkantokac34@gmail.com>

    SPDX-License-Identifier: GPL-2.0-or-later
*/

import QtQuick 2.7
import QtQuick.Controls 2.0 as QQC2
import QtQuick.Layouts 1.3 as Layouts
import QtQuick.Window 2.15

import org.kde.kcm 1.1 as KCM
import org.kde.kirigami 2.14 as Kirigami
import org.kde.kquickcontrols 2.0

import "components"
import org.kde.plasma.core 2.0 as PlasmaCore
Kirigami.ApplicationItem {
    id: root
    pageStack.globalToolBar.style:  Kirigami.ApplicationHeaderStyle.None
    pageStack.columnView.columnResizeMode: Kirigami.ColumnView.SingleColumn
    pageStack.defaultColumnWidth: Kirigami.Units.gridUnit * 20

    property size sizeHint: Qt.size(formLayout.width, Math.round(1.3 * formLayout.height))
    property size minimumSizeHint: Qt.size(formLayout.width/2, Math.round(1.3 * formLayout.height))

    property alias deviceIndex: deviceSelector.currentIndex
    signal changeSignal()

    property QtObject device
    property int deviceCount: backend.deviceCount

    property bool loading: false
    property bool lighttheme:PlasmaCore.Theme.viewBackgroundColor=="#ffffff" 
    property var backgroundcolor: PlasmaCore.Theme.viewBackgroundColor
    property var textcolor:PlasmaCore.Theme.textColor
    property var bordercolor:lighttheme?"#CCCCCC":"#2D2D2D"
    property var spaceline:lighttheme?"#F0F0F0":"#2D2D2D"
    enabled: deviceCount > 0

    function resetModel(index) {
        deviceCount = backend.deviceCount
        formLayout.enabled = deviceCount
        deviceSelector.enabled = deviceCount > 1

        loading = true
        if (deviceCount) {
            device = deviceModel[index]
            deviceSelector.model = deviceModel
            deviceSelector.currentIndex = index
        } else {
            deviceSelector.model = [""]
        }
        loading = false
    }

    function syncValuesFromBackend() {
        loading = true
        deviceEnabled.load()
        leftHanded.load()
        middleEmulation.load()
        accelSpeed.load()
        accelProfile.load()
        naturalScroll.load()
        scrollFactor.load()
        loading = false
    }


    

    pageStack.initialPage: Kirigami.ScrollablePage {

        spacing: Kirigami.Units.smallSpacing

        Kirigami.FormLayout {
            id: formLayout
            enabled: deviceCount

            Item {
                Layouts.Layout.fillWidth: true

                //DEVICE
                Rectangle {
                    id: deviceItem
                    anchors.horizontalCenter:parent.horizontalCenter
                    color: backgroundcolor
                    height:48
                    width:558
                    border.color: bordercolor
                    border.width: 1
                    radius: 10
                    QQC2.Label{
                        anchors.verticalCenter: parent.verticalCenter
                        anchors.left: parent.left
                        anchors.leftMargin: 23
                        text: i18nd("kcmmouse", "Device")
                        font.pixelSize: 14
                        color: textcolor
                        font.family: "SourceHanSansSC-Regular"
                    }
                    QQC2.ComboBox {
                        id: deviceSelector
                        anchors.verticalCenter: parent.verticalCenter
                        anchors.right: parent.right
                        anchors.rightMargin: 24
                        width: 192
                        height:30
                        enabled: deviceCount > 1
                        model: deviceModel
                        textRole: "name"
                        onCurrentIndexChanged: {
                            if (deviceCount) {
                                device = deviceModel[currentIndex]
                                if (!loading) {
                                    changeSignal()
                                }
                            }
                            root.syncValuesFromBackend()
                        }
                    }

                }

                //NORMAL
                Rectangle{
                    id:normalitem
                    anchors.top : deviceItem.bottom
                    anchors.horizontalCenter:parent.horizontalCenter
                    color: "transparent" 
                    height:180
                    width:558
                    QQC2.Label{
                        anchors.top: parent.top
                        anchors.topMargin: 16
                        anchors.left: parent.left
                        text: i18nd("kcmmouse", "General")
                        font.pixelSize: 14
                        color: textcolor
                        font.family: "SourceHanSansSC-Regular"
                    }
                    Rectangle {
                        anchors.top: parent.top
                        anchors.topMargin: 39
                        anchors.left: parent.left
                        color: backgroundcolor
                        height:142
                        width:558
                        border.color: bordercolor
                        border.width: 1
                        radius: 10
                        QQC2.Label{
                            anchors.top: parent.top
                            anchors.topMargin: 15
                            anchors.left: parent.left
                            anchors.leftMargin: 23
                            text: i18nd("kcmmouse", "Device enabled")
                            font.pixelSize: 14
                            color: textcolor
                            font.family: "SourceHanSansSC-Regular"
                        }
                        KcmSwitch{
                            id: deviceEnabled
                            anchors.top: parent.top
                            anchors.topMargin: 15
                            anchors.left: parent.left
                            anchors.leftMargin: 498
                            function load() {
                                if (!formLayout.enabled) {
                                    checked = false
                                    return
                                }
                                enabled = device.supportsDisableEvents
                                checked = enabled && device.enabled
                            }

                            onCheckedChanged: {
                                if (enabled && !root.loading) {
                                    device.enabled = checked
                                    root.changeSignal()
                                }
                            }
                            // ToolTip {
                            //     text: i18nd("kcmmouse", "Accept input through this device.")
                            // }
                        }
                        Rectangle{
                            anchors.top: parent.top
                            anchors.topMargin: 47
                            width:parent.width 
                            color:spaceline
                            height:1}
                        QQC2.Label{
                            anchors.top: parent.top
                            anchors.topMargin: 62
                            anchors.left: parent.left
                            anchors.leftMargin: 23
                            text: i18nd("kcmmouse", "Left handed mode")
                            font.pixelSize: 14
                            color: textcolor
                            font.family: "SourceHanSansSC-Regular"
                        }
                        KcmSwitch{
                            id: leftHanded
                            anchors.top: parent.top
                            anchors.topMargin: 62
                            anchors.left: parent.left
                            anchors.leftMargin: 498


                            function load() {
                                if (!formLayout.enabled) {
                                    checked = false
                                    return
                                }
                                enabled = device.supportsLeftHanded
                                checked = enabled && device.leftHanded
                            }

                            onCheckedChanged: {
                                if (enabled && !root.loading) {
                                    device.leftHanded = checked
                                    root.changeSignal()
                                }
                            }

                            // ToolTip {
                            //     text: i18nd("kcmmouse", "Swap left and right buttons.")
                            // }
                            
                        }
                        Rectangle{
                            anchors.top: parent.top
                            anchors.topMargin: 94
                            width:parent.width 
                            color:spaceline
                            height:1}
                        QQC2.Label{
                            anchors.top: parent.top
                            anchors.topMargin: 108
                            anchors.left: parent.left
                            anchors.leftMargin: 23
                            text: i18nd("kcmmouse", "Press left and right buttons for middle-click")
                            font.pixelSize: 14
                            color: textcolor
                            font.family: "SourceHanSansSC-Regular"
                        }
                        KcmSwitch{
                            id: middleEmulation
                            anchors.top: parent.top
                            anchors.topMargin: 108
                            anchors.left: parent.left
                            anchors.leftMargin: 498
                            function load() {
                                if (!formLayout.enabled) {
                                    checked = false
                                    return
                                }
                                enabled = device.supportsMiddleEmulation
                                checked = enabled && device.middleEmulation
                            }

                            onCheckedChanged: {
                                if (enabled && !root.loading) {
                                    device.middleEmulation = checked
                                    root.changeSignal()
                                }
                            }
                            // ToolTip {
                            //     text: i18nd("kcmmouse", "Clicking left and right button simultaneously sends middle button click.")
                            // }
                        }
                    }
                }

                //指针
                Rectangle{
                    id:pointeritem
                    anchors.top : normalitem.bottom
                    anchors.horizontalCenter:parent.horizontalCenter
                    color: "transparent" 
                    height:135
                    width:558
                    QQC2.Label{
                        anchors.top: parent.top
                        anchors.topMargin: 16
                        anchors.left: parent.left
                        text: i18nd("kcmmouse", "Pointer")
                        font.pixelSize: 14
                        color: textcolor
                        font.family: "SourceHanSansSC-Regular"
                    }
                    
                    Rectangle {
                        anchors.top: parent.top
                        anchors.topMargin: 39
                        anchors.left: parent.left
                        color: backgroundcolor 
                        height:95
                        width:558
                        border.color: bordercolor
                        border.width: 1
                        radius: 10
                        QQC2.Label{
                            anchors.top: parent.top
                            anchors.topMargin: 15
                            anchors.left: parent.left
                            anchors.leftMargin: 23
                            text: i18nd("kcmmouse", "Pointer speed")
                            font.pixelSize: 14
                            color: textcolor
                            font.family: "SourceHanSansSC-Regular"
                        }
                        KcmSlider {
                            id: accelSpeed
                            anchors.top: parent.top
                            anchors.topMargin: 25
                            anchors.left: parent.left
                            anchors.leftMargin:342
                            from: 1
                            to: 11
                            function load() {
                                enabled = device.supportsPointerAcceleration
                                if (!enabled) {
                                    value = 0.2
                                    return
                                }
                                // transform libinput's pointer acceleration range [-1, 1] to slider range [1, 11]
                                //value = 4.5 * device.pointerAcceleration + 5.5
                                value = 6 + device.pointerAcceleration / 0.2
                            }

                            onValueChanged: {
                                if (device != undefined && enabled && !root.loading) {
                                    // transform slider range [1, 10] to libinput's pointer acceleration range [-1, 1]
                                    // by *10 and /10, we ignore the floating points after 1 digit. This prevents from
                                    // having a libinput value like 0.60000001
                                    device.pointerAcceleration = Math.round(((value-6) * 0.2) * 10) / 10
                                    root.changeSignal()
                                }
                            }
                        }
                        Rectangle{
                            anchors.top: parent.top
                            anchors.topMargin: 47
                            width:parent.width 
                            color:spaceline
                            height:1}
                        QQC2.Label{
                            anchors.top: parent.top
                            anchors.topMargin: 62
                            anchors.left: parent.left
                            anchors.leftMargin: 23
                            text: i18nd("kcmmouse", "Acceleration profile")
                            font.pixelSize: 14
                            color: textcolor
                            font.family: "SourceHanSansSC-Regular"
                        }
                        QQC2.ComboBox {
                            id: accelProfile
                            anchors.top: parent.top
                            anchors.topMargin: 56
                            anchors.left: parent.left
                            anchors.leftMargin: 342
                            width: 192
                            height:30
                            enabled: deviceCount > 1
                            model: [i18nd("kcmmouse", "Flat"),i18nd("kcmmouse", "Adaptive") ]

                            function load() {
                                enabled = device.supportsPointerAccelerationProfileAdaptive
                                if (!enabled) {
                                    accelProfile. currentIndex=-1
                                    return
                                }
                                if(device.pointerAccelerationProfileAdaptive) {
                                    accelProfile. currentIndex= 1
                                } else {
                                    accelProfile. currentIndex= 0
                                }
                            }

                            function syncCurrent() {
                                if(accelProfile. currentIndex < 0){
                                    return
                                }
                                if (enabled && !root.loading) {
                                    device.pointerAccelerationProfileFlat = (accelProfile. currentIndex ==0)?true : false
                                    device.pointerAccelerationProfileAdaptive = (accelProfile. currentIndex ==1)?true : false
                                    root.changeSignal()
                                }
                            }

                            onCurrentIndexChanged:accelProfile.syncCurrent()


                        }
                    }
                }

                //SCROLL
                Rectangle{
                    id:scrollitem
                    anchors.top : pointeritem.bottom
                    anchors.horizontalCenter:parent.horizontalCenter
                    color: "transparent" 
                    height:135
                    width:558
                    QQC2.Label{
                        anchors.top: parent.top
                        anchors.topMargin: 16
                        anchors.left: parent.left
                        text: i18nd("kcmmouse", "Scrolling")
                        font.pixelSize: 14
                        color: textcolor
                        font.family: "SourceHanSansSC-Regular"
                    }
                    Rectangle {
                        anchors.top: parent.top
                        anchors.topMargin: 39
                        anchors.left: parent.left
                        color: backgroundcolor
                        height:95
                        width:558
                        border.color: bordercolor
                        border.width: 1
                        radius: 10
                        QQC2.Label{
                            anchors.top: parent.top
                            anchors.topMargin: 15
                            anchors.left: parent.left
                            anchors.leftMargin: 23
                            text: i18nd("kcmmouse", "Invert scroll direction")
                            font.pixelSize: 14
                            color: textcolor
                            font.family: "SourceHanSansSC-Regular"
                        }
                        KcmSwitch{
                            id: naturalScroll
                            anchors.top: parent.top
                            anchors.topMargin: 15
                            anchors.left: parent.left
                            anchors.leftMargin: 498
                            function load() {
                                enabled = device.supportsNaturalScroll
                                checked = enabled && device.naturalScroll
                            }

                            onCheckedChanged: {
                                if (enabled && !root.loading) {
                                    device.naturalScroll = checked
                                    root.changeSignal()
                                }

                            }

                            // ToolTip {
                            //     text: i18nd("kcmmouse", "Touchscreen like scrolling.")
                            // }

                        }
                        Rectangle{
                            anchors.top: parent.top
                            anchors.topMargin: 47
                            width:parent.width 
                            color:spaceline
                            height:1}
                        QQC2.Label{
                            anchors.top: parent.top
                            anchors.topMargin: 62
                            anchors.left: parent.left
                            anchors.leftMargin: 23
                            text: i18nd("kcm_touchpad", "Scrolling speed:")
                            font.pixelSize: 14
                            color: textcolor
                            font.family: "SourceHanSansSC-Regular"
                        }
                        KcmSlider {
                            id: scrollFactor
                            anchors.top: parent.top
                            anchors.topMargin: 69
                            anchors.left: parent.left
                            anchors.leftMargin:342
                            from: 0
                            to: 14
                            stepSize :1
                            property variant values : [
                                0.1,
                                0.3,
                                0.5,
                                0.75,
                                1, // default
                                1.5,
                                2,
                                3,
                                4,
                                5,
                                7,
                                9,
                                12,
                                15,
                                20
                            ]
                            function load() {
                                let index = values.indexOf(device.scrollFactor)
                                if (index === -1) {
                                    index = values.indexOf(1);
                                }
                                value = index
                            }

                            onMoved: {
                                device.scrollFactor = values[value]
                                root.changeSignal()
                            }

                            
                        }


                        
                    }
                }


            }
        }
    }
    // Kirigami.ScrollablePage {
    //     id: buttonPage

    //     MouseArea {
    //         // Deliberately using MouseArea on the page instead of a TapHandler on the button, so we can capture clicks anywhere
    //         id: buttonCapture
    //         property var lastButton: {}

    //         anchors.fill: parent
    //         enabled: newBinding.checked
    //         preventStealing: true
    //         acceptedButtons: Qt.AllButtons & ~(Qt.LeftButton | Qt.RightButton | Qt.MiddleButton)
    //         onClicked: {
    //             lastButton = buttonMappings.extraButtons.find(entry => Qt[entry.buttonName] == mouse.button)
    //             newBinding.visible = false
    //             newKeySequenceItem.visible = true
    //             newKeySequenceItem.startCapturing()
    //         }
    //     }

    //    Layouts.ColumnLayout {
    //         Kirigami.FormLayout {
    //             id: buttonLayout
    //             twinFormLayouts: otherLayout
    //             Repeater {
    //                 id: buttonMappings

    //                 readonly property var extraButtons: Array.from({length: 24}, (value,index) => ({
    //                     buttonName: "ExtraButton" + (index + 1),
    //                     button: Qt["ExtraButton" + (index + 1)],
    //                     label: i18ndc("kcmmouse", "@label for assigning an action to a numbered button", "Extra Button %1:", index + 1)
    //                 }))

    //                 function load() {
    //                     model = Qt.binding(() => extraButtons.filter(entry => backend.buttonMapping.hasOwnProperty(entry.buttonName)))
    //                 }

    //                 delegate: KeySequenceItem {
    //                     Kirigami.FormData.label: modelData.label

    //                     keySequence: backend.buttonMapping[modelData.buttonName]

    //                     modifierlessAllowed: true
    //                     multiKeyShortcutsAllowed: false
    //                     checkForConflictsAgainst: ShortcutType.None

    //                     onCaptureFinished: {
    //                         let copy = backend.buttonMapping;
    //                         copy[modelData.buttonName] = keySequence
    //                         backend.buttonMapping = copy
    //                         root.changeSignal()
    //                     }
    //                 }
    //             }
    //         }

    //         Kirigami.InlineMessage {
    //             id: explanationLabel
    //             Layouts.Layout.fillWidth: true
    //             visible: newBinding.checked || newKeySequenceItem.visible
    //             text: newBinding.visible ? i18ndc("kcmmouse","@action:button", "Press the mouse button for which you want to add a key binding") :
    //                 i18ndc("kcmmouse","@action:button, %1 is the translation of 'Extra Button %1' from above", "Enter the new key combination for %1", buttonCapture.lastButton.label)
    //             actions: [
    //                 Kirigami.Action {
    //                     icon.name: "dialog-cancel"
    //                     text: i18ndc("kcmmouse", "@action:button", "Cancel")
    //                     onTriggered: {
    //                         newKeySequenceItem.visible = false;
    //                         newBinding.visible = true
    //                         newBinding.checked = false
    //                     }
    //                 }
    //             ]
    //         }

    //         Kirigami.FormLayout {
    //             id: otherLayout
    //             twinFormLayouts: buttonLayout

    //             QQC2.Button {
    //                 id:newBinding
    //                 checkable: true
    //                 text: checked ? i18ndc("kcmmouse", "@action:button", "Press a mouse button ") :
    //                     i18ndc("kcmmouse", "@action:button, Bind a mousebutton to keyboard key(s)", "Add Binding…")
    //                 icon.name: "list-add"
    //             }
    //             KeySequenceItem {
    //                 id: newKeySequenceItem
    //                 visible: false

    //                 modifierlessAllowed: true
    //                 multiKeyShortcutsAllowed: false
    //                 checkForConflictsAgainst: ShortcutType.None

    //                 onCaptureFinished: {
    //                     visible = false
    //                     newBinding.visible = true
    //                     newBinding.checked = false
    //                     let copy = backend.buttonMapping;
    //                     copy[buttonCapture.lastButton.buttonName] = keySequence
    //                     backend.buttonMapping = copy
    //                     root.changeSignal()
    //                 }
    //             }


    //             Item {
    //                 Kirigami.FormData.isSection: true
    //             }

    //             QQC2.Button  {
    //                 onClicked: root.pageStack.pop()
    //                 text: i18ndc("kcmmouse", "@action:button", "Go back")
    //                 icon.name: "go-previous"

    //             }
    //         }
    //     }
    // }
}
